import { NzMessageService } from 'ng-zorro-antd';
import { FormBuilder, FormControl, FormGroup, ValidationErrors } from '@angular/forms';
import * as _ from 'lodash';
import { Observable, Observer } from 'rxjs';
import { Injector } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { UpdateMessageService } from '@core/update-message.service';
import { ApiService } from '@core/api.service';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
import { ExportFileService } from '@core/exportFile';
import { environment } from '../../environments/environment';

// 封装多个组件反复调用的方法
export abstract class UniversalFunctionsUtil {
  apiService: ApiService;
  exportFile: ExportFileService;
  domSanitizer: DomSanitizer;
  message: NzMessageService;
  ums: UpdateMessageService;
  router: Router;
  router2: Router;
  activeRoute: ActivatedRoute;
  fb: FormBuilder;
  validateForm: FormGroup;
  displayData = [];
  today = new Date();
  itemsTotal: number;
  oldPage = 1;
  oldSize = 10;
  pageIndex = 1;
  pageSize = 10;
  loadingData = true;
  allChecked = false;
  indeterminate = false;
  submitting = false;
  visible = false;
  recognition = 'VC_MATERIAL$ID';
  totalPrice = 0; // 物资申请总价
  isVisible = false; // 模态框的出现
  queryId: string;
  fileName: string;

  constructor(
    private baseInjector: Injector,

  ) {
    this.apiService = this.baseInjector.get(ApiService);
    this.message = this.baseInjector.get(NzMessageService);
    this.ums = this.baseInjector.get(UpdateMessageService);
    this.router = this.baseInjector.get(Router);
    this.router2 = this.baseInjector.get(Router);
    this.activeRoute = this.baseInjector.get(ActivatedRoute);
    this.fb = this.baseInjector.get(FormBuilder);
    this.domSanitizer = this.baseInjector.get(DomSanitizer);
    this.exportFile = this.baseInjector.get(ExportFileService);
  }

  // 标签正常化显示
  normalizeTag = (rawHTML: string): SafeHtml => this.domSanitizer.bypassSecurityTrustHtml(rawHTML);

  getState = (state: boolean): boolean => this.loadingData = state;

  // 价格和数量相乘精度精确到两位
  numRound = (a, b): number => a && b ? _.round(a * b, 2) : 0;

  // 只能选中一条
  checkOne = (ind: number): void => this.displayData.forEach((data, k: number) => data.checked = ind == k);

  // 通用表单防止输入空格
  customizedValidator = (control: FormControl) => (
    Observable.create((observer: Observer<ValidationErrors>) => {
      setTimeout(() => {
        observer.next(control.value.trim() ? null : { error: true, space: true });
        observer.complete();
      }, 300);
    })
  )

  refreshStatus(): void {
    const allChecked = this.displayData.length && this.displayData.every(value => value.checked);
    const allUnChecked = this.displayData.every(value => !value.checked);
    this.allChecked = allChecked;
    this.indeterminate = (!allChecked) && (!allUnChecked);
  }

  checkAll(value: boolean): void {
    this.displayData.forEach(data => data.checked = value);
    this.refreshStatus();
  }

  // 通用表单清空
  resetForm(e: MouseEvent) {
    e && e.preventDefault();
    this.validateForm.reset();
    for (const key in this.validateForm.controls) {
      this.controlReset(key);
    }
  }

  controlReset(key: string) {
    const control = this.validateForm.controls[key];
    control.markAsPristine();
    control.updateValueAndValidity();
  }

  // 文件导出
  export(address) { 
    const urlSegments = {
      'repairform': environment.apiBase + '/csmis/ymTtempworkapply/export.jwt', // 高速铁路临时要点维修文件导出
      'reportrepair': environment.apiBase + '/csmis/emerSkywinreport/export.jwt', // 紧急修天窗文件导出
    };
    this.exportFile.getDown(urlSegments[address] + '?id=' + this.queryId, this.fileName);
  }

  // 无法获取接口数据失败错误提示
  errorHandle(response) {
    this.message.create('error', JSON.stringify(response), { nzDuration: 1500 });
    this.loadingData = false;
    this.submitting = false;
  }

  // 获取接口数据提示
  remoteMessage(response) {
    if (response.type === 'success') {
      this.message.success(response.message, { nzDuration: 1800 });
    } else if (response.type === 'fail') {
      this.message.warning(response.message, { nzDuration: 1200 });
    }
  }
}
